package com.igrowing.api.appclientsdk.client;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.igrowing.api.appclientsdk.model.UserTest;
import com.igrowing.api.appclientsdk.utils.Encrypt;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TestCLient {

    private String accessKey;
    private String secretKey;


    public TestCLient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public TestCLient() {
    }

    public String getNameByGet(String url,String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3 = HttpUtil.get("http://localhost:8123/api/name/?", paramMap);
        System.out.println(result3);
        return result3;
    }


    public String getNameByPost(String url, String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3 = HttpUtil.post(url, paramMap);
        System.out.println(result3);
        return result3;
    }


    public String getNameByJson(String url, UserTest user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post("http://localhost:8123/api/name/user")
                .addHeaders(getHeader(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String body = httpResponse.body();
        System.out.println(body);
        System.out.println("getNameByJson已被调用");
        return body;

    }

    private Map<String, String> getHeader(String body) {
        HashMap<String, String> HeaderHashMap = new HashMap<>();

        HeaderHashMap.put("accessKey", accessKey);
        HeaderHashMap.put("body", body);
        HeaderHashMap.put("Key", Encrypt.encrypt(body, secretKey));

        return HeaderHashMap;

    }


}